<template>
  <div class="page white-stage">
    <div class="container my-card-main">
      <div class="group upload-main">
        <div class="upload-body" >
          <div class="cell upload-qrcode" id="pickfiles">
            <div>
              <div class="upload-qrcode-body"  v-if="!card.card_qrcode">
                <i class="upload-ico">+</i>
                <span class="upload-qrcode-txt">上传微信二维码</span>
              </div>

              <div class="upload-qrcode-body"  v-if="card.card_qrcode">
                <img :src="card.card_qrcode"/>
              </div>
            </div>
          </div>

          <div class="cell my-name border-bottom txt-center">
            <input type="text" v-model="card.name" placeholder="姓名"/>
          </div>

          <div class="cell my-phone border-bottom">
            <input type="text" v-model="card.card_mobile" placeholder="手机"/>
          </div>

          <div class="cell my-desc border-radius mgt transparent">
            <textarea placeholder="个人介绍" v-model="card.card_user_desc"></textarea>
          </div>
        </div>
      </div>

      <div class="group">
        <div class="cell mgt">
          <span class="save-btn" @click="saveCard">保存</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import Vue from 'vue';
  import axios from 'axios';
  import store from '../store'
  import env from '../../env'
  import Q from 'q'

  export default{

  data () {
     return {
     card: {},
     my:{
       name: '',
     },

     isQiniuInstalled: false
     }
  },

  methods: {

    loadScript(url, callback) {
    var script = document.createElement("script");
    script.type = "text/javascript";
    if(typeof(callback) != "undefined"){
      if (script.readyState) {
      script.onreadystatechange = function () {
        if (script.readyState == "loaded" || script.readyState == "complete") {
        script.onreadystatechange = null;
        callback();
        }
      };
      } else {
      script.onload = function () {
        callback();
      };
      }
    }
    script.src = url;
    document.body.appendChild(script);
    },

    saveCard () {
    let that = this;

    store.dispatch('saveCard', that.card).then((response) =>{
      if(response.data.errcode === 0) {
      alert('保存成功!');
      } else {
      console.log('系统出错请联系管理员:', JSON.stringify(response.data));
      }
    }).catch((error)=>{
      console.log(error);
    });

    // let response = {
    //   "errcode": 0,
    //   "errmsg": "接口调用成功!",
    //   "results": {
    //   "card_status": "WSC",
    //   "card_user_desc": "人生的路上我们每个人都背负着各种各样的十字架在艰难前行。它也许是我们的学习，也许是我们的工作，也许是我们的感情。但是，正是这些责任和义务，构成了我们在这个世界上存在着的理由和价值。所以，请不要埋怨学习的繁重，工作的劳苦，感情的负担，因为真正的快乐，是奋战后的结果，没有经历深刻的痛苦，我们也就体会不到酣畅淋漓的快乐！",
    //   "card_qrcode": "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1490691488&di=b3bea06795a040809c5cd4732e0cffa0&src=http://www.zyue.com/upload/addr/er_20140725105541.png",
    //   "card_mobile": 15013199008
    //   }
    // };

    // if(response.errcode == 0) {
    //   that.$router.back();
    // } else {
    //   alert('系统出错，请联系管理员!');
    // }
    },

    getCard () {

    let that = this;

    store.dispatch('getCard').then(function(response){
      that.card = response.data.results;
      that.card.name = that.card.name || that.loginUser.username;
    });

    // let response = {
    //   "errcode": 0,
    //   "errmsg": "接口调用成功!",
    //   "results": {
    //   "card_status": "WSC",
    //   "card_user_desc": "人生的路上我们每个人都背负着各种各样的十字架在艰难前行。它也许是我们的学习，也许是我们的工作，也许是我们的感情。但是，正是这些责任和义务，构成了我们在这个世界上存在着的理由和价值。所以，请不要埋怨学习的繁重，工作的劳苦，感情的负担，因为真正的快乐，是奋战后的结果，没有经历深刻的痛苦，我们也就体会不到酣畅淋漓的快乐！",
    //   "card_qrcode": "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1490691488&di=b3bea06795a040809c5cd4732e0cffa0&src=http://www.zyue.com/upload/addr/er_20140725105541.png",
    //   "card_mobile": 15013199008
    //   }
    // };
    //
    // that.card = response.results;
    },

    uploadQrcode () {

      if(this.isQiniuInstalled === true) {

      let uptoken_url = env.CRM_API_HOST+'/users/'+this.token+'/upload_token';
      let that = this;

      console.log('www');
      try {
        axios.get(uptoken_url).then((response) => {
        if(response.data.errcode == 0) {

          let uptoken = response.data.results.token;
          let domain = response.data.results.domain;

          console.log('token :', Qiniu, domain)
          console.log(document.getElementById('pickfiles'))

          let uploader = Qiniu.uploader({
             runtimes: 'html5,flash,html4',
             browse_button: document.getElementById('pickfiles'),
            //  container: 'container',
             drop_element: 'container',
             max_file_size: '1000mb',
             flash_swf_url: 'bower_components/plupload/js/Moxie.swf',
             dragdrop: true,
             chunk_size: '1000mb',
             multi_selection: false,
            //  uptoken_url: $('#uptoken_url').val(),
             uptoken:uptoken,
             domain: domain,
             get_new_uptoken: false,
             // downtoken_url: '/downtoken',
             // unique_names: true,
             // save_key: true,
             // x_vars: {
             //   'id': '1234',
             //   'time': function(up, file) {
             //     var time = (new Date()).getTime();
             //     // do something with 'time'
             //     return time;
             //   },
             // },
             auto_start: true,
             log_level: 5,
             init: {
               'FilesAdded': function(up, files) {
                //  $('table').show();
                //  $('#success').hide();
                //  plupload.each(files, function(file) {
                //    var progress = new FileProgress(file, 'fsUploadProgress');
                //    progress.setStatus("ç­‰å¾…...");
                //    progress.bindUploadCancel(up);
                //  });
               },
               'BeforeUpload': function(up, file) {
               that.$vux.loading.show({
                 text: 'Loading'
               })
                //  var progress = new FileProgress(file, 'fsUploadProgress');
                //  var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                //  if (up.runtime === 'html5' && chunk_size) {
                //    progress.setChunkProgess(chunk_size);
                //  }
               },
               'UploadProgress': function(up, file) {
                //  var progress = new FileProgress(file, 'fsUploadProgress');
                //  var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                //  progress.setProgress(file.percent + "%", file.speed, chunk_size);
                console.log(file,1)
               },
               'UploadComplete': function(event, files, info) {
                //  $('#success').show();
                console.log('success', file, info)
                let file = files.pop();
                that.card.card_qrcode = domain+'/'+file.name;
                that.$vux.loading.hide();
               },
               'FileUploaded': function(up, file, info) {
                //  var progress = new FileProgress(file, 'fsUploadProgress');
                //  progress.setComplete(up, info);
               },
               'Error': function(up, err, errTip) {
                //  $('table').show();
                //  var progress = new FileProgress(err.file, 'fsUploadProgress');
                //  progress.setError();
                //  progress.setStatus(errTip);
               }
                 // ,
                 // 'Key': function(up, file) {
                 //   var key = "";
                 //   // do something with key
                 //   return key
                 // }
             }
           });

           uploader.bind('FileUploaded', function() {
             console.log('hello man,a file is uploaded');
           });

          // domain为七牛空间对应的域名，选择某个空间后，可通过 空间设置->基本设置->域名设置 查看获取
          // uploader为一个plupload对象，继承了所有plupload的方法
          console.log('============初始化qiniu完毕============')
        } else {
          console.log('初始化qiniu出错!', JSON.stringify(response.data))
        }
        }).catch((errcode)=>{
          console.log(errcode)
        });

      } catch(e) {
        console.log(e)
      }

      // let response = {
      //   "errcode": 0,
      //   "errmsg": "接口调用成功!",
      //   "results": {
      //   "token": "6EZmwsqQYeHvlaA44_LwiBAePez-rjpOv4jwg4t4:cYU1nbpCi9jzuejkwhstLZ9wWeQ=:eyJzY29wZSI6Im1xY3JtIiwiZGVhZGxpbmUiOjE0OTA3MjEwNjEsInVwSG9zdHMiOlsiaHR0cDpcL1wvdXAucWluaXUuY29tIiwiaHR0cDpcL1wvdXBsb2FkLnFpbml1LmNvbSIsIi1IIHVwLnFpbml1LmNvbSBodHRwOlwvXC8xODMuMTM2LjEzOS4xNiJdfQ==",
      //   "domain": "http://ocuvbzm86.bkt.clouddn.com"
      //   }
      // }
      }

    },

    initQiniuApiCallback () {
    console.log('初始化qiniu')
    console.log(window['Qiniu'], this)
    this.isQiniuInstalled = true;
    this.uploadQrcode();
    }
  },

  mounted () {

    let that = this;

    that.loadScript(env.MOXIE, function () {
      that.loadScript(env.PUPLOAD_CDN, function () {
      that.loadScript(env.QINIU_CDN,function () {
        that.initQiniuApiCallback();
        success(success)
      });
      });
    });

    this.callJsApi('biz.navigation.setTitle',{title:'我的名片'});
    this.getCard();
  },

  components:{

  },
  computed:{
    loginUser () {
    return this.$store.state.app.user;
    },

    token () {
    return this.$store.state.app.token;
    },

    domain () {
    return this.$store.state.app.token;
    }
  }
  }
</script>


<style lang="less">
  @import "../less/mixins/placeholder.less";
  @import "../less/index.less";

  .my-card-main {
    width:100%;
    background-color: white;

    .upload-main{
      width:82%;
      margin: 10px auto 0;
      border:1px solid #97D2FF;
      display: block;
      background: url("@{host}/img/my_card.png") no-repeat 0 0;
      background-size: 100% auto;

      .upload-body{
        width: 70%;
        padding-bottom: 10px;
        margin: 0 auto;
      }
    }

    .upload-qrcode {
      @upload-qrcode-size: 150px;
      width: @upload-qrcode-size;
      height: @upload-qrcode-size;
      background-color: #79B3DC;
      opacity: 0.85;
      margin:20px auto ;
      // display: table;
      // table-layout: fixed;
      overflow: hidden;

      .upload-qrcode-body{

        width: 100%;
        vertical-align: middle;
        height: @upload-qrcode-size;

        &>*{
        display: block;
        font-style: normal;
        text-align: center;
        height: 100%;
        object-fit: cover;
        width: 100%;
        color:white;
        }
      }
    }

    .cell {

    input{
      border:none;
      display: block;
      line-height: 16px;
      width: 100%;
      padding: 5px 0;
      font-size: 14px;

      .placeholder({
        text-align: center;
      })
    }

    &.border-bottom{
      border-bottom: 1px solid #97D2FF;
      margin: 10px 0;
    }

    &.border-radius{
      border: 1px solid #97D2FF;
      margin: 10px 0;
      border-radius: 4px;
    }

    &.mgt{
      margin-top: 30px;
    }



    textarea {
      border: 0;
      display: block;
      width: 100%;
      font-size: 14px;
      background-color:rgba(255,255,255,0.1);

      @textarea-size:130px;

      height: @textarea-size;

      .placeholder({
        text-align: center;
        font-size: 14px;
        line-height: @textarea-size;
      })

    }
    }



    .save-btn{
    width: 90%;
    display: block;
    background-color: #39ADFF;
    color: white;
    text-align: center;
    margin: 0 auto;
    border-radius: 4px;
    padding: 10px 0;
    }
  }
</style>
